
/**
  ******************************************************************************
  * Copyright 2021 The Microbee Authors. All Rights Reserved.
  * 
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  * 
  * http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  * 
  * @file       fms_servos.c
  * @author     baiyang
  * @date       2023-7-7
  ******************************************************************************
  */

/*----------------------------------include-----------------------------------*/
#include "fms.h"

#include <uITC/uITC.h>
#include <uITC/uITC_msg.h>

#include <common/time/gp_time.h>
#include <battery_monitor/battery_monitor.h>
/*-----------------------------------macro------------------------------------*/

/*----------------------------------typedef-----------------------------------*/

/*---------------------------------prototype----------------------------------*/

/*----------------------------------variable----------------------------------*/

/*-------------------------------------os-------------------------------------*/

/*----------------------------------function----------------------------------*/
/* Set the flight control servos based on the current calculated values

  This function operates by first building up output values for
  channels using set_servo() and set_radio_out(). Using
  set_radio_out() is for when a raw PWM value of output is given which
  does not depend on any output scaling. Using set_servo() is for when
  scaling and mixing will be needed.

  Finally servos_output() is called to push the final PWM values
  for output channels
*/
void fms_set_servos(void)
{
    // start with output corked. the cork is released when we run
    // servos_output(), which is run from all code paths in this
    // function
    srv_channels_cork();

    // do any transition updates for quadplane
#if HAL_QUADPLANE_ENABLED
    quadplane.update();
#endif

    if (fms.control_mode == (mode_base_t)&fms.mode_auto && fms.auto_state.idle_mode) {
        // special handling for balloon launch
        fms_set_servos_idle();
        fms_servos_output();
        return;
    }

    if (fms.control_mode != (mode_base_t)&fms.mode_manual) {
        fms_set_servos_controlled();
    }

    // setup flap outputs
    fms_set_servos_flaps();

    // set airbrake outputs
    fms_airbrake_update();

    // slew rate limit throttle
    fms_throttle_slew_limit(k_throttle);

    int8_t min_throttle = 0;
#if AP_ICENGINE_ENABLED
    if (g2.ice_control.allow_throttle_while_disarmed()) {
        min_throttle = MAX(fms.aparm.throttle_min, 0);
    }
    const float base_throttle = srv_channels_get_output_scaled(k_throttle);
#endif

    if (!mb_arming_is_armed()) {
        //Some ESCs get noisy (beep error msgs) if PWM == 0.
        //This little segment aims to avoid this.
        switch (mb_arming_required()) { 
        case ARMING_REQUIRED_NO:
            //keep existing behavior: do nothing to radio_out
            //(don't disarm throttle channel even if AP_Arming class is)
            break;

        case ARMING_REQUIRED_YES_ZERO_PWM:
            srv_channels_set_output_pwm(k_throttle, 0);
            srv_channels_set_output_pwm(k_throttleLeft, 0);
            srv_channels_set_output_pwm(k_throttleRight, 0);
            break;

        case ARMING_REQUIRED_YES_MIN_PWM:
        default:
            srv_channels_set_output_scaled(k_throttle, min_throttle);
            srv_channels_set_output_scaled(k_throttleLeft, min_throttle);
            srv_channels_set_output_scaled(k_throttleRight, min_throttle);
            break;
        }
    }

#if AP_ICENGINE_ENABLED
    float override_pct = srv_channels_get_output_scaled(k_throttle);
    if (g2.ice_control.throttle_override(override_pct, base_throttle)) {
        // the ICE controller wants to override the throttle for starting, idle, or redline
        srv_channels_set_output_scaled(k_throttle, override_pct);
#if HAL_QUADPLANE_ENABLED
        quadplane.vel_forward.integrator = 0;
#endif
    }
#endif  // AP_ICENGINE_ENABLED

    // run output mixer and send values to the hal for output
    fms_servos_output();
}

/*
  setup servos for idle mode
  Idle mode is used during balloon launch to keep servos still, apart
  from occasional wiggle to prevent freezing up
 */
void fms_set_servos_idle(void)
{
    int16_t servo_value;
    // move over full range for 2 seconds
    if (fms.auto_state.idle_wiggle_stage != 0) {
        fms.auto_state.idle_wiggle_stage += 2;
    }
    if (fms.auto_state.idle_wiggle_stage == 0) {
        servo_value = 0;
    } else if (fms.auto_state.idle_wiggle_stage < 50) {
        servo_value = fms.auto_state.idle_wiggle_stage * (4500 / 50);
    } else if (fms.auto_state.idle_wiggle_stage < 100) {
        servo_value = (100 - fms.auto_state.idle_wiggle_stage) * (4500 / 50);
    } else if (fms.auto_state.idle_wiggle_stage < 150) {
        servo_value = (100 - fms.auto_state.idle_wiggle_stage) * (4500 / 50);
    } else if (fms.auto_state.idle_wiggle_stage < 200) {
        servo_value = (fms.auto_state.idle_wiggle_stage-200) * (4500 / 50);
    } else {
        fms.auto_state.idle_wiggle_stage = 0;
        servo_value = 0;
    }
    srv_channels_set_output_scaled(k_aileron, servo_value);
    srv_channels_set_output_scaled(k_elevator, servo_value);
    srv_channels_set_output_scaled(k_rudder, servo_value);
    srv_channels_set_output_to_trim(k_throttle);

    srv_channels_output_ch_all();
}

/*
  setup output channels all non-manual modes
 */
void fms_set_servos_controlled(void)
{
#if 0
    if (fms.flight_stage == FWFS_LAND) {
        // allow landing to override servos if it would like to
        fms.landing.override_servos();
    }
#endif

    // convert 0 to 100% (or -100 to +100) into PWM
    int8_t min_throttle = fms.aparm.throttle_min;
    int8_t max_throttle = fms.aparm.throttle_max;;

    if (min_throttle < 0 && !fms_allow_reverse_thrust()) {
        // reverse thrust is available but inhibited.
        min_throttle = 0;
    }

    bool flight_stage_determines_max_throttle = false;
    if (fms.flight_stage == FWFS_TAKEOFF || 
        fms.flight_stage == FWFS_ABORT_LANDING
        ) {
        flight_stage_determines_max_throttle = true;
    }
#if HAL_QUADPLANE_ENABLED
    if (quadplane.in_transition()) {
        flight_stage_determines_max_throttle = true;
    }
#endif
    if (flight_stage_determines_max_throttle) {
        if (fms.aparm.takeoff_throttle_max != 0) {
            max_throttle = fms.aparm.takeoff_throttle_max;
        } else {
            max_throttle = fms.aparm.throttle_max;
        }
    } 
#if 0
else if (fms.landing.is_flaring()) {
        min_throttle = 0;
    }
#endif

    // conpensate for battery voltage drop
    fms_throttle_voltage_comp(&min_throttle, &max_throttle);

    // apply watt limiter
    fms_throttle_watt_limiter(&min_throttle, &max_throttle);

    srv_channels_set_output_scaled(k_throttle,
                                    math_constrain_float(srv_channels_get_output_scaled(k_throttle), min_throttle, max_throttle));

    if (!mb_arming_is_armed_and_safety_off()) {
        if (mb_arming_required() == ARMING_REQUIRED_YES_ZERO_PWM) {
            srv_channels_set_output_limit(k_throttle, SRV_ZERO_PWM);
            srv_channels_set_output_limit(k_throttleLeft, SRV_ZERO_PWM);
            srv_channels_set_output_limit(k_throttleRight, SRV_ZERO_PWM);
        } else {
            srv_channels_set_output_scaled(k_throttle, 0.0f);
            srv_channels_set_output_scaled(k_throttleLeft, 0.0f);
            srv_channels_set_output_scaled(k_throttleRight, 0.0f);
        }
    } else if (fms_suppress_throttle()) {
        srv_channels_set_output_scaled(k_throttle, 0.0f); // default
#if 0
        // throttle is suppressed (above) to zero in final flare in auto mode, but we allow instead thr_min if user prefers, eg turbines:
        if (landing.is_flaring() && landing.use_thr_min_during_flare() ) {
            srv_channels_set_output_scaled(k_throttle, fms.aparm.throttle_min.get());
        }
#endif
        if (fms.g.throttle_suppress_manual) {
            // manual pass through of throttle while throttle is suppressed
            srv_channels_set_output_scaled(k_throttle, fms_get_throttle_input(true));
        }
    } else if (fms.control_mode == (mode_base_t)&fms.mode_stabilize ||
               fms.control_mode == (mode_base_t)&fms.mode_training ||
               fms.control_mode == (mode_base_t)&fms.mode_acro ||
               fms.control_mode == (mode_base_t)&fms.mode_fbwa ||
               fms.control_mode == (mode_base_t)&fms.mode_autotune) {
        // a manual throttle mode
        if (!rcs_has_valid_input()) {
            srv_channels_set_output_scaled(k_throttle, 0.0f);
        } else if (fms.g.throttle_passthru_stabilize) {
            // manual pass through of throttle while in FBWA or
            // STABILIZE mode with THR_PASS_STAB set
            srv_channels_set_output_scaled(k_throttle, fms_get_throttle_input(true));
        } else {
            // get throttle, but adjust center to output TRIM_THROTTLE if flight option set
            srv_channels_set_output_scaled(k_throttle,
                                            math_constrain_int16(fms_get_adjusted_throttle_input(true), min_throttle, max_throttle));
        }
    } else if (mode_is_guided_mode(fms.control_mode) &&
               fms.guided_throttle_passthru) {
        // manual pass through of throttle while in GUIDED
        srv_channels_set_output_scaled(k_throttle, fms_get_throttle_input(true));
#if HAL_QUADPLANE_ENABLED
    } else if (quadplane.in_vtol_mode()) {
        float fwd_thr = 0;
        // if armed and not spooled down ask quadplane code for forward throttle
        if (quadplane.motors->armed() &&
            quadplane.motors->get_desired_spool_state() != AP_Motors::DesiredSpoolState::SHUT_DOWN) {

            fwd_thr = math_constrain_float(quadplane.forward_throttle_pct(), min_throttle, max_throttle);
        }
        srv_channels_set_output_scaled(k_throttle, fwd_thr);
#endif  // HAL_QUADPLANE_ENABLED
    }

    // let EKF know to start GSF yaw estimator before takeoff movement starts so that yaw angle is better estimated
    const float throttle = srv_channels_get_output_scaled(k_throttle);
    if (!fms_is_flying() && mb_arming_is_armed()) {
        // Check if rate of change of velocity along X axis exceeds 1-g which normally indicates a throw.
        // Tests with hand carriage of micro UAS indicates that a 1-g threshold does not false trigger prior
        // to the throw, but there is margin to increase this threshold if false triggering becomes problematic.
        const float accel_x_due_to_gravity = GRAVITY_MSS * fms.ahrs->sin_pitch;
        const float accel_x_due_to_throw = fms.ahrs->acc.x - accel_x_due_to_gravity;
        bool throw_detected = accel_x_due_to_throw > GRAVITY_MSS;
        bool throttle_up_detected = throttle > fms.aparm.throttle_cruise;
#if 0
        if (throw_detected || throttle_up_detected) {
            plane.ahrs.set_takeoff_expected(true);
        }
#endif
    }
}

/*
  Scale the throttle to conpensate for battery voltage drop
 */
void fms_throttle_voltage_comp(int8_t *min_throttle, int8_t *max_throttle)
{
    // return if not enabled, or setup incorrectly
    if (!math_flt_positive(fms.g.fwd_thr_batt_voltage_min) || fms.g.fwd_thr_batt_voltage_min >= fms.g.fwd_thr_batt_voltage_max) {
        return;
    }

    float batt_voltage_resting_estimate = battmonitor_voltage_resting_estimate(fms.g.fwd_thr_batt_idx);
    // Return for a very low battery
    if (batt_voltage_resting_estimate < 0.25f * fms.g.fwd_thr_batt_voltage_min) {
        return;
    }

    // constrain read voltage to min and max params
    batt_voltage_resting_estimate = math_constrain_float(batt_voltage_resting_estimate,fms.g.fwd_thr_batt_voltage_min,fms.g.fwd_thr_batt_voltage_max);

    // don't apply compensation if the voltage is excessively low
    if (batt_voltage_resting_estimate < 1) {
        return;
    }

    // Scale the throttle up to compensate for voltage drop
    // Ratio = 1 when voltage = voltage max, ratio increases as voltage drops
    const float ratio = fms.g.fwd_thr_batt_voltage_max / batt_voltage_resting_estimate;

    // Scale the throttle limits to prevent subsequent clipping
    *min_throttle = (int8_t)(MAX((ratio * (float)(*min_throttle)), -100));
    *max_throttle = (int8_t)(MIN((ratio * (float)(*max_throttle)),  100));

    srv_channels_set_output_scaled(k_throttle, math_constrain_float(srv_channels_get_output_scaled(k_throttle) * ratio, -100, 100));
}

/*
  calculate any throttle limits based on the watt limiter
 */
void fms_throttle_watt_limiter(int8_t *min_throttle, int8_t *max_throttle)
{
    uint32_t now = time_millis();
    if (battmonitor_overpower_detected()) {
        // overpower detected, cut back on the throttle if we're maxing it out by calculating a limiter value
        // throttle limit will attack by 10% per second
        
        if (math_flt_positive(srv_channels_get_output_scaled(k_throttle)) && // demanding too much positive thrust
            fms.throttle_watt_limit_max < (*max_throttle) - 25 &&
            now - fms.throttle_watt_limit_timer_ms >= 1) {
            // always allow for 25% throttle available regardless of battery status
            fms.throttle_watt_limit_timer_ms = now;
            fms.throttle_watt_limit_max++;
        } else if (math_flt_negative(srv_channels_get_output_scaled(k_throttle)) &&
                   (*min_throttle) < 0 && // reverse thrust is available
                   fms.throttle_watt_limit_min < -(*min_throttle) - 25 &&
                   now - fms.throttle_watt_limit_timer_ms >= 1) {
            // always allow for 25% throttle available regardless of battery status
            fms.throttle_watt_limit_timer_ms = now;
            fms.throttle_watt_limit_min++;
        }
        
    } else if (now - fms.throttle_watt_limit_timer_ms >= 1000) {
        // it has been 1 second since last over-current, check if we can resume higher throttle.
        // this throttle release is needed to allow raising the max_throttle as the battery voltage drains down
        // throttle limit will release by 1% per second
        if (srv_channels_get_output_scaled(k_throttle) > fms.throttle_watt_limit_max && // demanding max forward thrust
            fms.throttle_watt_limit_max > 0) { // and we're currently limiting it
            fms.throttle_watt_limit_timer_ms = now;
            fms.throttle_watt_limit_max--;
        } else if (srv_channels_get_output_scaled(k_throttle) < fms.throttle_watt_limit_min && // demanding max negative thrust
                   fms.throttle_watt_limit_min > 0) { // and we're limiting it
            fms.throttle_watt_limit_timer_ms = now;
            fms.throttle_watt_limit_min--;
        }
    }
    
    *max_throttle = math_constrain_int16((*max_throttle), 0, (*max_throttle) - fms.throttle_watt_limit_max);
    if ((*min_throttle) < 0) {
        *min_throttle = math_constrain_int16((*min_throttle), (*min_throttle) + fms.throttle_watt_limit_min, 0);
    }
}

/* We want to suppress the throttle if we think we are on the ground and in an autopilot controlled throttle mode.

   Disable throttle if following conditions are met:
   *       1 - We are in Circle mode (which we use for short term failsafe), or in FBW-B or higher
   *       AND
   *       2 - Our reported altitude is within 10 meters of the home altitude.
   *       3 - Our reported speed is under 5 meters per second.
   *       4 - We are not performing a takeoff in Auto mode or takeoff speed/accel not yet reached
   *       OR
   *       5 - Home location is not set
   *       OR
   *       6- Landing does not want to allow throttle
*/
bool fms_suppress_throttle(void)
{
    uitc_sensor_gps vehicle_gps_position;
    itc_copy_from_hub(ITC_ID(sensor_gps),  &vehicle_gps_position);

#if 0
#if PARACHUTE == ENABLED
    if (control_mode->does_auto_throttle() && parachute.release_initiated()) {
        // throttle always suppressed in auto-throttle modes after parachute release initiated
        throttle_suppressed = true;
        return true;
    }
#endif

    if (landing.is_throttle_suppressed()) {
        return true;
    }
#endif
    if (!fms.throttle_suppressed) {
        // we've previously met a condition for unsupressing the throttle
        return false;
    }
    if (!mode_does_auto_throttle(fms.control_mode)) {
        // the user controls the throttle
        fms.throttle_suppressed = false;
        return false;
    }

    bool gps_movement = (vehicle_gps_position.fix_type >= uITC_GPS_OK_FIX_2D && vehicle_gps_position.vel_m_s >= 5);
    
    if ((fms.control_mode == (mode_base_t)&fms.mode_auto &&
         fms.auto_state.takeoff_complete == false) ||
        fms.control_mode == (mode_base_t)&fms.mode_takeoff) {

        uint32_t launch_duration_ms = ((int32_t)fms.g.takeoff_throttle_delay)*100 + 2000;
        if (fms_is_flying() &&
            time_millis() - fms.started_flying_ms > MAX(launch_duration_ms, 5000U) && // been flying >5s in any mode
            fms_adjusted_relative_altitude_cm() > 500 && // are >5m above AGL/home
            labs(fms.ahrs->pitch_sensor_cd) < 3000 && // not high pitch, which happens when held before launch
            gps_movement) { // definite gps movement
            // we're already flying, do not suppress the throttle. We can get
            // stuck in this condition if we reset a mission and cmd 1 is takeoff
            // but we're currently flying around below the takeoff altitude
            fms.throttle_suppressed = false;
            return false;
        }
#if 0
        if (fms_auto_takeoff_check()) {
            // we're in auto takeoff 
            fms.throttle_suppressed = false;
            fms.auto_state.baro_takeoff_alt = ahrs_get_relative_position_u_home(fms.ahrs);
            return false;
        }
#endif
        // keep throttle suppressed
        return true;
    }
    
    if (fabsf(fms.relative_altitude) >= 10.0f) {
        // we're more than 10m from the home altitude
        fms.throttle_suppressed = false;
        return false;
    }

    if (gps_movement) {
        // if we have an airspeed sensor, then check it too, and
        // require 5m/s. This prevents throttle up due to spiky GPS
        // groundspeed with bad GPS reception
#if AP_AIRSPEED_ENABLED
        if ((!ahrs.airspeed_sensor_enabled()) || airspeed.get_airspeed() >= 5) {
            // we're moving at more than 5 m/s
            throttle_suppressed = false;
            return false;        
        }
#else
        // no airspeed sensor, so we trust that the GPS's movement is truthful
        fms.throttle_suppressed = false;
        return false;
#endif
    }

#if HAL_QUADPLANE_ENABLED
    if (quadplane.is_flying()) {
        fms.throttle_suppressed = false;
        return false;
    }
#endif

    // throttle remains suppressed
    return true;
}

/*
  setup flap outputs
 */
void fms_set_servos_flaps(void)
{
    // Auto flap deployment
    int8_t auto_flap_percent = 0;
    int8_t manual_flap_percent = 0;

    // work out any manual flap input
    if (fms.channel_flap != NULL && rcs_has_valid_input()) {
        manual_flap_percent = rc_percent_input(fms.channel_flap);
    }

    if (mode_does_auto_throttle(fms.control_mode)) {
        int16_t flapSpeedSource = 0;
        if (ahrs_airspeed_sensor_enabled(fms.ahrs)) {
            flapSpeedSource = fms.target_airspeed_cm * 0.01f;
        } else {
            flapSpeedSource = fms.aparm.throttle_cruise;
        }
        if (fms.g.flap_2_speed != 0 && flapSpeedSource <= fms.g.flap_2_speed) {
            auto_flap_percent = fms.g.flap_2_percent;
        } else if ( fms.g.flap_1_speed != 0 && flapSpeedSource <= fms.g.flap_1_speed) {
            auto_flap_percent = fms.g.flap_1_percent;
        } //else flaps stay at default zero deflection

#if 0
        if (control_mode == &mode_thermal) {
            auto_flap_percent = g2.soaring_controller.get_thermalling_flap();
        }
#endif

        /*
          special flap levels for takeoff and landing. This works
          better than speed based flaps as it leads to less
          possibility of oscillation
         */
        switch (fms.flight_stage) {
            case FWFS_TAKEOFF:
            case FWFS_ABORT_LANDING:
                if (fms.g.takeoff_flap_percent != 0) {
                    auto_flap_percent = fms.g.takeoff_flap_percent;
                }
                break;
            case FWFS_NORMAL:
                if (fms.g.takeoff_flap_percent != 0 && fms_in_preLaunch_flight_stage()) {
                    // TODO: move this to a new FLIGHT_PRE_TAKEOFF stage
                    auto_flap_percent = fms.g.takeoff_flap_percent;
                }
                break;
            case FWFS_LAND:
                if (landing_get_flap_percent() != 0) {
                  auto_flap_percent = landing_get_flap_percent();
                }
                break;
            default:
                break;
        }
    }

    // manual flap input overrides auto flap input
    if (abs(manual_flap_percent) > auto_flap_percent) {
        auto_flap_percent = manual_flap_percent;
    }

    srv_channels_set_output_scaled(k_flap_auto, auto_flap_percent);
    srv_channels_set_output_scaled(k_flap, manual_flap_percent);

    srv_channels_set_slew_rate(k_flap_auto, fms.g.flap_slewrate, 100, fms.FAST_Dt);
    srv_channels_set_slew_rate(k_flap, fms.g.flap_slewrate, 100, fms.FAST_Dt);

    // output to flaperons, if any
    fms_flaperon_update();
}

/*
  setup flaperon output channels
 */
void fms_flaperon_update()
{
    /*
      flaperons are implemented as a mixer between aileron and a
      percentage of flaps. Flap input can come from a manual channel
      or from auto flaps.
     */
    float aileron = srv_channels_get_output_scaled(k_aileron);
    float flap_percent = srv_channels_get_slew_limited_output_scaled(k_flap_auto);
    float flaperon_left  = math_constrain_float(aileron + flap_percent * 45, -4500, 4500);
    float flaperon_right = math_constrain_float(aileron - flap_percent * 45, -4500, 4500);
    srv_channels_set_output_scaled(k_flaperon_left, flaperon_left);
    srv_channels_set_output_scaled(k_flaperon_right, flaperon_right);
}

/*
 set airbrakes based on reverse thrust and/or manual input RC channel
 */
void fms_airbrake_update(void)
{
    // Calculate any manual airbrake input from RC channel option.
    float manual_airbrake_percent = 0;

    if (fms.channel_airbrake != NULL && !fms.failsafe.rc_failsafe && fms.failsafe.throttle_counter == 0) {
        manual_airbrake_percent = rc_percent_input(fms.channel_airbrake);
    }

    // Calculate auto airbrake from negative throttle.
    float throttle_min = fms.aparm.throttle_min;
    float airbrake_pc = 0;

    float throttle_pc = srv_channels_get_output_scaled(k_throttle);

    if (throttle_min < 0) {
#if 0
        if (landing.is_flaring()) {
            // Full airbrakes during the flare.
            airbrake_pc = 100;
        }
        else 
#endif
        {
            // Determine fraction between zero and full negative throttle.
            airbrake_pc = math_constrain_float(-throttle_pc, 0, 100);
        }
    }

    // Manual overrides auto airbrake setting.
    if (airbrake_pc < manual_airbrake_percent) {
        airbrake_pc = manual_airbrake_percent;
    }

    // Output to airbrake servo types.
    srv_channels_set_output_scaled(k_airbrake, airbrake_pc);
}

/*
  run configured output mixer. This takes calculated servo_out values
  for each channel and calculates PWM values, then pushes them to
  hal.rcout
 */
void fms_servos_output(void)
{
    srv_channels_cork();

    // support twin-engine aircraft
    fms_servos_twin_engine_mix();

    // run vtail and elevon mixers
    fms_channel_function_mixer(k_aileron, k_elevator, k_elevon_left, k_elevon_right);
    fms_channel_function_mixer(k_rudder,  k_elevator, k_vtail_right, k_vtail_left);

#if HAL_QUADPLANE_ENABLED
    // cope with tailsitters and bicopters
    quadplane.tailsitter.output();
    quadplane.tiltrotor.bicopter_output();
#endif

    // support forced flare option
    fms_force_flare();

    // implement differential spoilers
    fms_dspoiler_update();

    //  set control surface servos to neutral
    fms_landing_neutral_control_surface_servos();

    // set rudder arm waiting for neutral control throws (rudder neutral, aileron/rt vtail/rt elevon to full right)
    if (fms_flight_option_enabled(FO_INDICATE_WAITING_FOR_RUDDER_NEUTRAL)) {
        fms_indicate_waiting_for_rud_neutral_to_takeoff();
    }

    // support MANUAL_RCMASK
    if (fms.g.manual_rc_mask != 0 && fms.control_mode == (mode_base_t)&fms.mode_manual) {
        srv_channels_copy_radio_in_out_mask((uint32_t)(fms.g.manual_rc_mask));
    }

    srv_channels_calc_pwm();

    srv_channels_output_ch_all();

    srv_channels_push();

    if (srv_channels_auto_trim_enabled()) {
        fms_servos_auto_trim();
    }

    uitc_actuator_controls actuator_controls = {0};
    uitc_actuator_outputs actuator_outputs = {0};

    actuator_controls.timestamp_us = time_micros64();
    actuator_outputs.timestamp_us  = actuator_controls.timestamp_us;
    actuator_controls.throttle = fms_throttle_percentage();

    for (uint8_t i=0; i<NUM_SERVO_CHANNELS; i++) {
        if (srvs.channels[i].output_pwm != 0) {
            actuator_controls.control[i] = (float)(srvs.channels[i].output_pwm - srvs.channels[i].servo_min) / (srvs.channels[i].servo_max - srvs.channels[i].servo_min);
        }
        actuator_outputs.output[i] = srvs.channels[i].output_pwm;
    }

    itc_publish(ITC_ID(vehicle_actuator_controls), &actuator_controls);
    itc_publish(ITC_ID(vehicle_actuator_outputs), &actuator_outputs);
}

/*
  support for twin-engine planes
 */
void fms_servos_twin_engine_mix(void)
{
    float throttle = srv_channels_get_output_scaled(k_throttle);
    float rud_gain = (float)(fms.g.rudd_dt_gain) * 0.01f;
    fms.rudder_dt = rud_gain * srv_channels_get_output_scaled(k_rudder) / SERVO_MAX;

    float throttle_left, throttle_right;

    if (throttle < 0 && fms_have_reverse_thrust() && fms_allow_reverse_thrust()) {
        // doing reverse thrust
        throttle_left  = math_constrain_float(throttle + 50 * fms.rudder_dt, -100, 0);
        throttle_right = math_constrain_float(throttle - 50 * fms.rudder_dt, -100, 0);
    } else if (throttle <= 0) {
        throttle_left  = throttle_right = 0;
    } else {
        // doing forward thrust
        throttle_left  = math_constrain_float(throttle + 50 * fms.rudder_dt, 0, 100);
        throttle_right = math_constrain_float(throttle - 50 * fms.rudder_dt, 0, 100);
    }
    if (!mb_arming_is_armed_and_safety_off()) {
        if (mb_arming_required() == ARMING_REQUIRED_YES_ZERO_PWM) {
            srv_channels_set_output_limit(k_throttleLeft, SRV_ZERO_PWM);
            srv_channels_set_output_limit(k_throttleRight, SRV_ZERO_PWM);
        } else {
            srv_channels_set_output_scaled(k_throttleLeft, 0);
            srv_channels_set_output_scaled(k_throttleRight, 0);
        }
    } else {
        srv_channels_set_output_scaled(k_throttleLeft, throttle_left);
        srv_channels_set_output_scaled(k_throttleRight, throttle_right);
        fms_throttle_slew_limit(k_throttleLeft);
        fms_throttle_slew_limit(k_throttleRight);
    }
}

void fms_throttle_slew_limit(Aux_servo_function_t func)
{
#if HAL_QUADPLANE_ENABLED
    const bool do_throttle_slew = (mode_does_auto_throttle(fms.control_mode) || quadplane.in_assisted_flight() || quadplane.in_vtol_mode());
#else
    const bool do_throttle_slew = mode_does_auto_throttle(fms.control_mode);
#endif

    if (!do_throttle_slew) {
        // only do throttle slew limiting in modes where throttle control is automatic
        srv_channels_set_slew_rate(func, 0.0, 100, fms.FAST_Dt);
        return;
    }

    uint8_t slewrate = fms.aparm.throttle_slewrate;
#if 0
    if (fms.control_mode == (mode_base_t)&fms.mode_auto) {
        if (fms.auto_state.takeoff_complete == false && fms.g.takeoff_throttle_slewrate != 0) {
            slewrate = fms.g.takeoff_throttle_slewrate;
        } else if (landing.get_throttle_slewrate() != 0 && fms.flight_stage == FWFS_LAND) {
            slewrate = landing.get_throttle_slewrate();
        }
    }
#endif
    if (fms.g.takeoff_throttle_slewrate != 0 &&
        (fms.flight_stage == FWFS_TAKEOFF ||
         fms.flight_stage == FWFS_VTOL)) {
        // for VTOL we use takeoff slewrate, which helps with transition
        slewrate = fms.g.takeoff_throttle_slewrate;
    }
#if HAL_QUADPLANE_ENABLED
    if (fms.g.takeoff_throttle_slewrate != 0 && quadplane.in_transition()) {
        slewrate = fms.g.takeoff_throttle_slewrate;
    }
#endif
    srv_channels_set_slew_rate(func, slewrate, 100, fms.FAST_Dt);
}

/*
  mixer for elevon and vtail channels setup using designated servo
  function values. This mixer operates purely on scaled values,
  allowing the user to trim and limit individual servos using the
  SERVOn_* parameters
 */
void fms_channel_function_mixer(Aux_servo_function_t func1_in, Aux_servo_function_t func2_in,
                                   Aux_servo_function_t func1_out, Aux_servo_function_t func2_out)
{
    // the order is setup so that non-reversed servos go "up", and
    // func1 is the "left" channel. Users can adjust with channel
    // reversal as needed
    float in1 = srv_channels_get_output_scaled(func1_in);
    float in2 = srv_channels_get_output_scaled(func2_in);

    // apply MIXING_OFFSET to input channels
    if (fms.g.mixing_offset < 0) {
        in2 *= (100 - fms.g.mixing_offset) * 0.01f;
    } else if (fms.g.mixing_offset > 0) {
        in1 *= (100 + fms.g.mixing_offset) * 0.01f;
    }
    
    float out1 = math_constrain_float((in2 - in1) * fms.g.mixing_gain, -4500, 4500);
    float out2 = math_constrain_float((in2 + in1) * fms.g.mixing_gain, -4500, 4500);
    srv_channels_set_output_scaled(func1_out, out1);
    srv_channels_set_output_scaled(func2_out, out2);
}

/*
  Set throttle,attitude(in Attitude.cpp), and tilt servos for forced flare by RCx_OPTION switch for landing in FW mode
  For Fixed Wind modes with manual throttle control only. Forces tilts up and throttle to THR_MIN.
  Throttle stick must be in idle deadzone. This allows non-momentary switch to be used and quick bailouts
  for go-arounds. Also helps prevent propstrike after landing with switch release on ground.
*/
void fms_force_flare(void)
{
#if HAL_QUADPLANE_ENABLED
    if (quadplane.in_transition() && mb_arming_is_armed()) { //allows for ground checking of flare tilts
        return;
    }
    if (mode_is_vtol_mode(fms.control_mode)) {
        return;
    }
    /* to be active must be:
       -manual throttle mode
       -in an enabled flare mode (RC switch active)
       -at zero thrust: in throttle trim dz except for sprung throttle option where trim is at hover stick
    */
    if (!mode_does_auto_throttle(fms.control_mode) && fms.flare_mode != FM_FLARE_DISABLED && fms_throttle_at_zero()) {
        int32_t tilt = -SERVO_MAX;  //this is tilts up for a normal tiltrotor if at zero thrust throttle stick      
        if (quadplane.tiltrotor.enabled() && (quadplane.tiltrotor.type == Tiltrotor::TILT_TYPE_BICOPTER)) {
            tilt = 0; // this is tilts up for a Bicopter
        }
        if (quadplane.tailsitter.enabled()) {
            tilt = SERVO_MAX; //this is tilts up for a tailsitter
        }
        srv_channels_set_output_scaled(k_motor_tilt, tilt);
        srv_channels_set_output_scaled(k_tiltMotorLeft, tilt);
        srv_channels_set_output_scaled(k_tiltMotorRight, tilt);
        srv_channels_set_output_scaled(k_tiltMotorRear, tilt);
        srv_channels_set_output_scaled(k_tiltMotorRearLeft, tilt);
        srv_channels_set_output_scaled(k_tiltMotorRearRight, tilt);
        float throttle_min = MAX(fms.aparm.throttle_min,0); //allows ICE to run if used but accounts for reverse thrust setups
        if (mb_arming_is_armed()) {  //prevent running motors if unarmed
            srv_channels_set_output_scaled(k_throttle, throttle_min);
            srv_channels_set_output_scaled(k_throttleLeft, throttle_min);
            srv_channels_set_output_scaled(k_throttleRight, throttle_min);
        }
    }
#endif
}

/*
  setup differential spoiler output channels

  Differential spoilers are a type of elevon that is split on each
  wing to give yaw control, mixed from rudder
 */
void fms_dspoiler_update(void)
{
    const int8_t bitmask = fms.g.crow_flap_options;
    const bool flying_wing       = (bitmask & CFO_FLYINGWING) != 0;
    const bool full_span_aileron = (bitmask & CFO_FULLSPAN) != 0;
    //progressive crow when option is set or RC switch is set to progressive 
    const bool progressive_crow   = (bitmask & CFO_PROGRESSIVE_CROW) != 0  || fms.crow_mode == CM_PROGRESSIVE; 

    // if flying wing use elevons else use ailerons
    float elevon_left;
    float elevon_right;
    if (flying_wing) {
        elevon_left = srv_channels_get_output_scaled(k_elevon_left);
        elevon_right = srv_channels_get_output_scaled(k_elevon_right);
    } else {
        const float aileron = srv_channels_get_output_scaled(k_aileron);
        elevon_left = -aileron;
        elevon_right = aileron;
    }

    const float rudder_rate = fms.g.dspoiler_rud_rate * 0.01f;
    const float rudder = srv_channels_get_output_scaled(k_rudder) * rudder_rate;
    float dspoiler_outer_left = elevon_left;
    float dspoiler_outer_right = elevon_right;

    float dspoiler_inner_left = 0;
    float dspoiler_inner_right = 0;

    // full span ailerons / elevons
    if (full_span_aileron) {
        dspoiler_inner_left = elevon_left;
        dspoiler_inner_right = elevon_right;
    }

    if (rudder > 0) {
        // apply rudder to right wing
        dspoiler_outer_right = math_constrain_float(dspoiler_outer_right + rudder, -4500, 4500);
        dspoiler_inner_right = math_constrain_float(dspoiler_inner_right - rudder, -4500, 4500);
    } else {
        // apply rudder to left wing
        dspoiler_outer_left = math_constrain_float(dspoiler_outer_left - rudder, -4500, 4500);
        dspoiler_inner_left = math_constrain_float(dspoiler_inner_left + rudder, -4500, 4500);
    }

    // limit flap throw used for aileron
    const int8_t aileron_matching = fms.g.crow_flap_aileron_matching;
    if (aileron_matching < 100) {
        // only do matching if it will make a difference
        const float aileron_matching_scaled = aileron_matching * 0.01;
        if (math_flt_negative(dspoiler_inner_left)) {
            dspoiler_inner_left *= aileron_matching_scaled;
        }
        if (math_flt_negative(dspoiler_inner_right)) {
            dspoiler_inner_right *= aileron_matching_scaled;
        }
    }

    int16_t weight_outer = fms.g.crow_flap_weight_outer;
    if (fms.crow_mode == CM_CROW_DISABLED) {   //override totally aileron crow if crow RC switch set to disabled
        weight_outer = 0;
    }
    const int16_t weight_inner = fms.g.crow_flap_weight_inner;
    if (weight_outer > 0 || weight_inner > 0) {
        /*
          apply crow flaps by apply the same split of the differential
          spoilers to both wings. Get flap percentage from k_flap_auto, which is set
          in set_servos_flaps() as the maximum of manual and auto flap control
         */
        const float flap_percent = srv_channels_get_slew_limited_output_scaled(k_flap_auto);

        if (math_flt_positive(flap_percent)) {
            float inner_flap_scaled = flap_percent;
            float outer_flap_scaled = flap_percent;
            if (progressive_crow) {
                // apply 0 - full inner from 0 to 50% flap then add in outer above 50%
                inner_flap_scaled = math_constrain_float(inner_flap_scaled * 2, 0,100);
                outer_flap_scaled = math_constrain_float(outer_flap_scaled - 50, 0,50) * 2;
            }
            // scale flaps so when weights are 100 they give full up or down
            dspoiler_outer_left  = math_constrain_float(dspoiler_outer_left  + outer_flap_scaled * weight_outer * 0.45f, -4500, 4500);
            dspoiler_inner_left  = math_constrain_float(dspoiler_inner_left  - inner_flap_scaled * weight_inner * 0.45f, -4500, 4500);
            dspoiler_outer_right = math_constrain_float(dspoiler_outer_right + outer_flap_scaled * weight_outer * 0.45f, -4500, 4500);
            dspoiler_inner_right = math_constrain_float(dspoiler_inner_right - inner_flap_scaled * weight_inner * 0.45f, -4500, 4500);
        }
    }

    srv_channels_set_output_scaled(k_dspoilerLeft1, dspoiler_outer_left);
    srv_channels_set_output_scaled(k_dspoilerLeft2, dspoiler_inner_left);
    srv_channels_set_output_scaled(k_dspoilerRight1, dspoiler_outer_right);
    srv_channels_set_output_scaled(k_dspoilerRight2, dspoiler_inner_right);
}

/*
    This sets servos to neutral if it is a control surface servo in auto mode
*/
void fms_landing_neutral_control_surface_servos(void)
{
#if 0
    if (!(landing.get_then_servos_neutral() > 0 &&
            control_mode == &mode_auto &&
            landing.get_disarm_delay() > 0 &&
            landing.is_complete() &&
            !arming.is_armed())) {
                return;
    }


    // after an auto land and auto disarm, set the servos to be neutral just
    // in case we're upside down or some crazy angle and straining the servos.
    for (uint8_t i = 0; i < NUM_SERVO_CHANNELS ; i++) {
            SRV_Channel *chan =srv_channels::srv_channel(i);
            if (chan == nullptr || !SRV_Channel::is_control_surface(chan->get_function())) {
                continue;
            }

            if (landing.get_then_servos_neutral() == 1) {
                srv_channels_set_output_scaled(chan->get_function(), 0);
            } else if (landing.get_then_servos_neutral() == 2) {
                srv_channels_set_output_limit(chan->get_function(), SRV_ZERO_PWM);
            }
    }
#endif
}

/*
  sets rudder/vtail , and elevon to indicator positions that we are in a rudder arming waiting for neutral stick state
*/
void fms_indicate_waiting_for_rud_neutral_to_takeoff(void)
{
    if (fms.takeoff_state.waiting_for_rudder_neutral)  {
        srv_channels_set_output_scaled(k_rudder, 0);
        fms_channel_function_mixer(k_rudder,  k_elevator, k_vtail_right, k_vtail_left);
        if (!srv_channels_function_assigned(k_rudder) && !srv_channels_function_assigned(k_vtail_left)) {
            // if no rudder indication possible, neutral elevons during wait becuase on takeoff stance they are usually both full up
            srv_channels_set_output_scaled(k_elevon_right, 0);
            srv_channels_set_output_scaled(k_elevon_left, 0);
        }
    }
}

/*
  implement automatic persistent trim of control surfaces with
  AUTO_TRIM=2, only available when SERVO_RNG_ENABLE=1 as otherwise it
  would impact R/C transmitter calibration
 */
void fms_servos_auto_trim(void)
{
    // only in auto modes and FBWA
    if (!mode_does_auto_throttle(fms.control_mode) && fms.control_mode != (mode_base_t)&fms.mode_fbwa) {
        return;
    }
    if (!mb_arming_is_armed_and_safety_off()) {
        return;
    }
    if (!fms_is_flying()) {
        return;
    }
#if HAL_QUADPLANE_ENABLED
    if (!quadplane.allow_servo_auto_trim()) {
        // can't auto-trim with quadplane motors running
        return;
    }
#endif
    if (abs(fms.nav_roll_cd) > 700 || abs(fms.nav_pitch_cd) > 700) {
        // only when close to level
        return;
    }
    uint32_t now = time_millis();
    if (now - fms.auto_trim.last_trim_check < 500) {
        // check twice a second. We want slow trim update
        return;
    }
    if (ahrs_get_speed_xy_cms(fms.ahrs) < 8 || fms.smoothed_airspeed < 8) {
        // only when definitely moving
        return;
    }

    // adjust trim on channels by a small amount according to I value
    float roll_I = rctrl_get_pid_info(&fms.roll_controller)->I;
    float pitch_I = pctrl_get_pid_info(&fms.pitch_controller)->I;

    srv_channels_adjust_trim(k_aileron, roll_I);
    srv_channels_adjust_trim(k_elevator, pitch_I);

    srv_channels_adjust_trim(k_elevon_left,  pitch_I - roll_I);
    srv_channels_adjust_trim(k_elevon_right, pitch_I + roll_I);

    srv_channels_adjust_trim(k_vtail_left,  pitch_I);
    srv_channels_adjust_trim(k_vtail_right, pitch_I);

    srv_channels_adjust_trim(k_flaperon_left,  roll_I);
    srv_channels_adjust_trim(k_flaperon_right, roll_I);

    // cope with various dspoiler options
    const int8_t bitmask = fms.g.crow_flap_options;
    const bool flying_wing       = (bitmask & CFO_FLYINGWING) != 0;
    const bool full_span_aileron = (bitmask & CFO_FULLSPAN) != 0;

    float dspoiler_outer_left = - roll_I;
    float dspoiler_inner_left = 0.0f;
    float dspoiler_outer_right = roll_I;
    float dspoiler_inner_right = 0.0f;

    if (flying_wing) {
        dspoiler_outer_left += pitch_I;
        dspoiler_outer_right += pitch_I;
    }
    if (full_span_aileron) {
        dspoiler_inner_left = dspoiler_outer_left;
        dspoiler_inner_right = dspoiler_outer_right;
    }

    srv_channels_adjust_trim(k_dspoilerLeft1,  dspoiler_outer_left);
    srv_channels_adjust_trim(k_dspoilerLeft2,  dspoiler_inner_left);
    srv_channels_adjust_trim(k_dspoilerRight1, dspoiler_outer_right);
    srv_channels_adjust_trim(k_dspoilerRight2, dspoiler_inner_right);

    fms.auto_trim.last_trim_check = now;

    if (now - fms.auto_trim.last_trim_save > 10000) {
        fms.auto_trim.last_trim_save = now;
        srv_channels_save_trim();
    }
}
/*------------------------------------test------------------------------------*/


